import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Button, Dialog, Drawer, Message, Box, Icon, Tab } from '@alifd/next';
import { t } from '@lingui/macro';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import { column, ENUMS, toSelectDataSource } from './stores/definitions';
import { useHistory, useParams } from 'react-router';
import DataForm from './components/DataForm';
import MoreFuncDropDown from '@/components/MoreFuncDropDown';

function ScSharePrice() {
  const { scRelevancyStore: store } = useStore();
  const [modal, setModal] = useState(null);
  const history = useHistory();
  const { id } = useParams();

  useEffect(() => {
    (async () => {
      await store.getCitiesStationAllMenu();
    })();
    return () => {
      store.data = [];
    };
  }, []);

  const handleSearch = (params) => {
    const { orderDate, ...searchArgs } = params.values;
    const [from, to] = orderDate || [];
    const { start, end } = params?.valueObjects || {};
    const [onCityId, onStationId] = store.formatArea(start || {});
    const [offCityId, offStationId] = store.formatArea(end || {});
    store.search = {
      from,
      to,
      onCityId,
      onStationId,
      offCityId,
      offStationId,
      ...searchArgs,
    };
  };

  const handleOpenAdd = () => {
    setModal({
      show: 'add',
      record: null,
    });
  };

  const handleOpenEdit = (result) => {
    setModal({
      show: 'edit',
      record: result,
    });
  };

  const handleOnCancel = () => {
    setModal({ show: null, record: null });
  };

  // 新增订单数据提交
  const handleCreate = async (result) => {
    if (!_.isEmpty(result)) {
      Dialog.confirm({
        content: t`确认创建该关联线路吗？`,
        onOk: async () => {
          try {
            await store.create(toJS(result));
            Message.success({ content: t`创建成功` });
          } catch (error) {
            Message.error({ content: t`创建失败`, duration: 7000 });
          }
          setModal([]);
        },
      });
    }
  };

  const handleDelete = (shiftId) => {
    Dialog.confirm({
      content: t`确认删除该线路吗？`,
      onOk: async () => {
        try {
          await store.remove(toJS(shiftId));
          Message.success({ content: t`删除成功` });
        } catch (e) {
          Message.error({ content: t`删除失败`, duration: 7000 });
          throw e;
        }
        handleOnCancel();
      },
    });
  };

  const handleUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        await store.update(toJS(result));
        Message.success({ content: t`修政成功` });
      } catch (error) {
        Message.error({ content: t`修政失败`, duration: 7000 });
      }
      handleOnCancel();
    }
  };

  return (
    <TauPage className="page-container">
      <Box direction="row" align="center" margin={10}>
        <Button
          type="normal"
          onClick={() => {
            history.goBack();
          }}
          style={{ marginLeft: '-10px', border: 0 }}
        >
          <Icon
            type="arrow-left"
            style={{ padding: 6, border: '1px solid #ccc', borderRadius: '50%', color: 'var(--btn-pure-primary-bg)' }}
          />
        </Button>
        <div>{t`专线线路关联配置`}</div>
      </Box>
      <TauActionPanel
        className="action-panel"
        onSearch={handleSearch}
        actions={[
          {
            name: 'btn-addLine',
            title: t`添加关联专线线路`,
            type: 'primary',
            onClick: () => handleOpenAdd(),
          },
        ]}
        searchItems={[
          {
            name: 'orderDate',
            type: 'date-range',
            props: {
              placeholder: [t`关联起始时间`, t`关联结束时间`],
            },
          },
          {
            name: 'start',
            type: 'sc-station',
            props: {
              placeholder: t`始发站点`,
              changeOnSelect: true,
              style: { minWidth: '160px' },
            },
          },
          {
            name: 'end',
            type: 'sc-station',
            props: {
              placeholder: t`结束站点`,
              changeOnSelect: true,
              style: { minWidth: '160px' },
            },
          },
          {
            name: 'enable',
            type: 'select',
            props: {
              dataSource: toSelectDataSource(ENUMS.enable),
              placeholder: t`是否启用`,
            },
          },
        ]}
      />
      <div className="content">
        <TauTable
          primaryKey="id"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          sort={store.tableSort}
          onFetch={(pg) => {
            store.pg = pg;
          }}
          loading={store.loading}
          dataSource={toJS(store.data)}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('routeName', { width: 88 }),
            column('lineGroup', { width: 300 }),
            column('enable', { width: 88 }),
            column('remarks', { width: 88 }),
            column('crDate', { width: 88 }),
            {
              title: t`操作`,
              dataIndex: 'id',
              width: 100,
              cell: (_, __, line) => {
                const menu = [
                  {
                    key: 'edit',
                    title: t`编辑`,
                    onClick: () => handleOpenEdit(line),
                  },
                  {
                    key: 'delete',
                    title: t`删除`,
                    color: 'red',
                    onClick: () => handleDelete(line.id),
                  },
                ];
                return <MoreFuncDropDown dropdownItems={menu} />;
              },
            },
          ]}
        />
      </div>
      <Drawer
        visible={ENUMS._drawer_title[modal?.show]}
        title={ENUMS._drawer_title[modal?.show]}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal({ ...modal, toClose: `toClose$${Date.now()}` })}
        style={{ maxWidth: '100%' }}
        width="90%"
      >
        <DataForm
          modal={modal}
          onSubmit={modal?.show === 'add' ? handleCreate : handleUpdate}
          onCancel={() => handleOnCancel()}
        />
      </Drawer>
    </TauPage>
  );
}

export default observer(ScSharePrice);
